﻿using RestApp.UI.Core;
using RestApp.UI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace RestApp.UI.Controllers
{
    public class AccountController : Controller
    {
        private IBusinessFactory _factory;
        public AccountController(IBusinessFactory factory)
        {
            _factory = factory;
        }

        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(LoginModel loginModel, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                loginModel.Login = loginModel.Login.Trim();
                loginModel.Password = loginModel.Password.Trim();

                if (!_factory.UsersLogic.VerifyUser(loginModel.Login, loginModel.Password))
                {
                    ModelState.AddModelError("", "Неверное имя пользователя или пароль");
                    return View();
                }
                else
                {
                    FormsAuthentication.SetAuthCookie(loginModel.Login, false);
                    return RedirectToAction("Index", "Home");
                }
            }
            ModelState.AddModelError("", "Пожалуйста, заполните форму корректными данными");
            return View(loginModel);
        }

        public void Logout()
        {
            FormsAuthentication.SignOut();
            FormsAuthentication.RedirectToLoginPage();
        }
    }
}